package ui.swing.textcomponent;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

public class TextPaneDemo extends JFrame {

	private static final long serialVersionUID = 172810750149749927L;

	private JTextPane textPane;

	public TextPaneDemo() {
		super("TextPaneDemo");
		setBounds(100, 100, 300, 300);
		
		textPane = new JTextPane();
		setYellow_Bold_20("This is Line 1,yellow,Bold,Size 20");
		setBlue_Italic_Bold_22("This is Line 2,blue,Italic,Bold,Size 22");
		setRed_UnderLine_Italic_24("This is Line 3,red,UnderLine,Italic,Size 24");
		
		getContentPane().add(textPane);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);

	}

	public void setYellow_Bold_20(String str) {
		SimpleAttributeSet attrset = new SimpleAttributeSet();
		StyleConstants.setForeground(attrset, Color.yellow);
		StyleConstants.setBold(attrset, true);
		insert(str,attrset);
	}

	public void setBlue_Italic_Bold_22(String str) {
		SimpleAttributeSet attrset = new SimpleAttributeSet();
		StyleConstants.setForeground(attrset, Color.blue);
		StyleConstants.setItalic(attrset, true);
		StyleConstants.setFontSize(attrset, 24);
		insert(str,attrset);
	}

	public void setRed_UnderLine_Italic_24(String str) {
		SimpleAttributeSet attrset = new SimpleAttributeSet();
		StyleConstants.setForeground(attrset, Color.red);
		StyleConstants.setUnderline(attrset, true);
		StyleConstants.setItalic(attrset, true);
		StyleConstants.setFontSize(attrset, 24);
		insert(str, attrset);
	}

	//这个方法最主要的用途是将字符串插入到JTextPane中
	public void insert(String str, AttributeSet attrset) {
		Document docs = textPane.getDocument(); // 利用getDocument()方法取得JTextPane的Document instance
		str+='\n';
		
		try {
			docs.insertString(docs.getLength(), str, attrset);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new TextPaneDemo();
	}
}
